/**
 * @description User 业务控制器
 * @author malin
 */

const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { getUserInfo, createUser } = require('../services/user')
const doCrypto = require('../utils/cryp')
const jwt = require('jsonwebtoken')
const { TOKEN_SECRET_KEY } = require('../conf/secretKeys')
const {
    userNameExisted,
    registerUserFailed,
    loginFailed
} = require('../model/ErrorInfo')

/**
 * 设置token
 * @param {object} payload 
 */
function setToken(payload) {
    return jwt.sign(payload, TOKEN_SECRET_KEY, { expiresIn: '1h' })
}

/**
 * 用户注册
 * @param {string} userName 
 * @param {string} password 
 * @param {number} gender 1 2 3
 */
async function register({ userName, password, gender }) {
    // 1、获取用户信息，看用户名是否存在
    const userInfo = await getUserInfo(userName)
    if (userInfo) {
        return new ErrorModel(userNameExisted)
    }
    // 2、不存在，则创建用户（调用service）
    try {
        let userInfo = await createUser({ userName, password: doCrypto(password), gender })
        return new SuccessModel()
    } catch(err) {
        console.error(err)
        return new ErrorModel(registerUserFailed)
    }
}

/**
 * 登录，签发token
 * @param {string} userName 
 * @param {string} password 
 */
async function login(userName, password) {
    const userInfo = await getUserInfo(userName, doCrypto(password))
    if (userInfo) {
        const token = setToken(userInfo)
        return new SuccessModel({
            token,
            userInfo
        })
    } else {
        return new ErrorModel(loginFailed)
    }
}

module.exports = {
    register,
    login
}
